#include "regexp.h"

RegExp::RegExp() : _pattern(0), _patext(0) { ; }

RegExp::RegExp(const RegExp &Regex)
{
   *this = Regex;
}

RegExp &
RegExp::operator= (const RegExp &Regex)
{
   _pattern = Regex._pattern;
   _patext = Regex._patext;

   return *this;
}

RegExp::~RegExp()
{
   if (_pattern) {
      pcre_free(_pattern);
   }
}

void
RegExp::compile(std::string &string)
{
   const char *error;
   int offset = 0;
   _pattern = pcre_compile(string.c_str(), 0, &error, &offset, NULL);
   if (_pattern)
      _patext = pcre_study(_pattern, 0, &error);
}

void
RegExp::compile(const char *string)
{
   std::string cstr = string;
   compile(cstr);
}

std::string
RegExp::search(std::string &string)
{
   std::string retval;
   if (string.length()) {
      char retstr[BUFSIZ];
      memset(retstr, '\0', BUFSIZ);

      int vector[PCRE_VECTOR];

      int rc = pcre_exec(_pattern, _patext, string.c_str(),
            string.length(), 0, 0, vector, PCRE_VECTOR);
      if (rc > 0)  {
         pcre_copy_substring(string.c_str(), vector, rc, 0, 
               retstr, sizeof(retstr));
         retval  = retstr;
      }

   }

   return retval;
}
